package cn.chengpengper.seckill.goods.application.event;

import cn.chengpengper.seckill.goods.application.cache.service.SeckillGoodsCacheService;
import cn.chengpengper.seckill.goods.application.cache.service.SeckillGoodsListCacheService;
import cn.chengpengper.seckill.goods.domain.event.SeckillGoodsEvent;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.event.EventHandler;
import com.alibaba.cola.event.EventHandlerI;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.util.Objects;

/**
 * @author chengpeng.hu
 */
@Slf4j
@EventHandler
@RequiredArgsConstructor
@ConditionalOnProperty(name = "message.mq.type", havingValue = "cola")
public class SeckillGoodsEventHandler implements EventHandlerI<Response, SeckillGoodsEvent> {

    private final SeckillGoodsCacheService seckillGoodsCacheService;

    private final SeckillGoodsListCacheService seckillGoodsListCacheService;

    @Override
    public Response execute(SeckillGoodsEvent seckillGoodsEvent) {
        log.info("SeckillGoodsEventHandler|接收到商品事件|{}", JSON.toJSON(seckillGoodsEvent));
        if (Objects.isNull(seckillGoodsEvent)) {
            log.info("SeckillGoodsEventHandler|事件参数错误");
            return Response.buildSuccess();
        }
        seckillGoodsCacheService.tryUpdateSeckillGoodsCacheByLock(seckillGoodsEvent.getId(), false);
        seckillGoodsListCacheService.tryUpdateSeckillGoodsListCacheByLock(seckillGoodsEvent.getActivityId(), false);
        return Response.buildSuccess();
    }
}
